package org.jfk.common.ctrl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.jfk.core.model.AttachmentFile;

import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

public class FileController extends Controller{
	private static Logger logger = Logger.getLogger(FileController.class);

	public void kindEditorUpload(){
		String fileType = getPara("dir");
		_upload(fileType);
	}
	
	public void upload(){
		 _upload(null);
	}
	
	public Integer _upload(String fileType){
		
		Integer fileId = null;
		
		String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
		//String temp = PathKit.getWebRootPath() + "/temp";
		//logger.debug("temp path = " + temp);
		//UploadFile file = getFile(fileFieldName, "/temp");
		UploadFile file = getFile();
		File source = file.getFile();
		String fileName = file.getFileName();
		String contentType = file.getContentType();
		
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String prefix = "upload";
        
        //没有告知类型则用文件后缀名进行判定
        if (fileType == null){
	        if(".png".equalsIgnoreCase(extension) || ".jpg".equalsIgnoreCase(extension) || ".gif".equalsIgnoreCase(extension)){
	        	fileType="image";
	        }else{
	        	fileType = "other";
	        }
        }
    	fileName = generateWord() + extension;
        Map json = new HashMap();
		fileType = fileType == null?"":fileType+"/";
        
        try{
	        FileInputStream fis = new FileInputStream(source);
	        
	        Properties props = PropKit.use("system_config.properties",Const.DEFAULT_ENCODING).getProperties(); 
	        String uploadPath = props.getProperty("upload.path");
	        
        	//如果未配置文件存储路径，则在本webapp的目录下（不推荐）存放
	        uploadPath = uploadPath == null ? PathKit.getWebRootPath() : uploadPath;
	        
	        File targetDir = new File(uploadPath + "/" + prefix + "/"+fileType
	                + path);  
	        
	        if (!targetDir.exists()) {
	            targetDir.mkdirs();
	        }
	        File target = new File(targetDir, fileName);
	        if (!target.exists()) {
	            target.createNewFile();
	        }
	        FileOutputStream fos = new FileOutputStream(target);
	        byte[] bts = new byte[300];
	        while (fis.read(bts, 0, 300) != -1) {
	            fos.write(bts, 0, 300);
	        }
	        fos.close();
	        fis.close();
	        
	        String fileUrl;
	        if (props.getProperty("upload.path") == null){
	        	String ctxPath = this.getRequest().getContextPath();
	        	fileUrl = ctxPath + "/" + prefix + "/"+fileType + path + "/" + fileName;
	        }else{
	        	fileUrl = "/" +prefix + "/"+fileType + path + "/" + fileName;
	        }
	        
	        AttachmentFile attachment = new AttachmentFile();
	        attachment.set("file_name", fileName);
	        attachment.set("file_type", contentType);
	        attachment.set("file_size", file.getFile().length()/1024d);
	        attachment.set("file_path", fileUrl);
	        attachment.save();
	        fileId = attachment.getInt("id");

	        source.delete();
	        
	        json.put("error", 0);
	        json.put("url", fileUrl);
	        json.put("file_id", fileId);
	        
        } catch (FileNotFoundException e) {
            json.put("error", 1);
            json.put("message", "上传出现错误，请稍后再上传");
        } catch (IOException e) {
            json.put("error", 1);
            json.put("message", "文件写入服务器出现错误，请稍后再上传");
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	json.put("error", 1);
        	json.put("message", "其他错误");
        }
       
        //super.renderText(JsonUtil.map2jsonStr(json));
        super.renderJson(json);
		return fileId;
	}
	
	public void uploadByData(){
		UploadFile file = getFile();
		String tableName = getPara("tableName");
		BigDecimal dataId = BigDecimal.valueOf(this.getParaToInt("dataId"));
		String fieldName = this.getPara("fieldName");
		Integer fileId = _upload(null);
		
		Record record = new Record();
		record.set("id", dataId);
		record.set(fieldName, fileId);
		Db.update(tableName, record);

		
	}
	

	/**
	 * 清除指定数据表中指向附件的外键
	 */
	public void clearByData(){
		UploadFile file = getFile();
		String tableName = getPara("tableName");
		int dataId = this.getParaToInt("dataId");
		String fieldName = this.getPara("fieldName");

		Record record = new Record();
		record.set("id", dataId);
		record.set(fieldName, null);
		Db.update(tableName, record);

		Map json = new HashMap();
        json.put("error", 0);
		
        super.renderJson(json);
	}	

    public void download(){
        String path = getPara(0);
        String img = PathKit.getWebRootPath() + "/img/u/" + path.replaceAll("_", "/");
        //ZipUtil.zip(img, PathKit.getWebRootPath() + "/img/temp/" + path);
        renderFile(img);
    }	
	
    private String generateWord() {
        String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };
        List<String> list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(5, 9);
        return result;
    }	
    

}
